//引入vue
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
//注册vuex
Vue.use(Vuex)


//状态
const state = {
    userinfo: JSON.parse(localStorage.getItem('userinfo')),
    useslist: [],
    productList: []
}
console.log(state.userinfo)

//mutations 主要用来操作state
const mutations = {
    UPDATE_USERINFO(state, userinfo) {
        localStorage.setItem('userinfo', JSON.stringify(userinfo))
        state.userinfo = userinfo
        console.log(state.userinfo)
    },
    //获取全局的userList数据
    GET_USERLIST(state, userlist) {
        //更新state里面的数据
        state.useslist = userlist
    },
    //修改state的productList数据
    GET_PRODUCTLIST(state, productList) {
        state.productList = productList
    }
}
const actions = {
    //请求数据，异步请求经过promise改同步
    GET_USERLIST({ commit }) {
        return new Promise((resolve, reject) => {
            axios.post('/api/findUser').then(res => {
                console.log(res)
                //更新mutations里面GET_USERLIST方法的数据
                commit('GET_USERLIST', res.data)
                resolve()
            })
        })
        // new promises()

    },

    //获取商品列表
    GET_PRODUCTLIST({ commit }) {
        return new Promise((resolve, reject) => {
            axios.post('/api/findProduct').then(res => {
                console.log(res)
                commit('GET_PRODUCTLIST', res.data)
                resolve()
            })
        })
    }

}
//使用getter赛选
const getters = {
    filtUserList: state => state.useslist.filter(v => v.age > 25)
}
//创建store仓库，暴露出去
export default new Vuex.Store({
    state,
    mutations,
    actions,
    getters
})